package com.clean.cleantotal.bean

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Environment
import androidx.lifecycle.LifecycleCoroutineScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.NetworkUtils
import com.clean.cleantotal.R
import com.clean.cleantotal.utils.MyDeviceUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

object DataUtils {
    fun getHomeList(): List<HomeBean> {
        val list = listOf(
            HomeBean(R.mipmap.green_home_offer, "Device Scan", "", FunType.DEVICE),
            HomeBean(R.mipmap.green_home_offera, "Large File", "", FunType.LARGE),
            HomeBean(R.mipmap.green_home_horse, "Battery Info", "", FunType.BATTERY),
            HomeBean(R.mipmap.green_home_flatten, "App Process", "", FunType.PROCESS),
        )
        list.forEachIndexed { index, homeBean ->
            homeBean.index = index
        }
        return list
    }

    fun getToolsList(): List<HomeBean> {
        return listOf(
            HomeBean(R.mipmap.green_tools_lock, "Empty Files", "", FunType.EMPTY),
            HomeBean(R.mipmap.green_tools_silk, "Compress Photo", "", FunType.COMPRESS),
            HomeBean(R.mipmap.green_tools_horse, "Tiktok Clean", "", FunType.TIK),
            HomeBean(R.mipmap.green_tools_flattenh, "Instagram Clean", "", FunType.INS),
            HomeBean(R.mipmap.green_tools_rainya, "Telegram Clean", "", FunType.TEL),
            HomeBean(R.mipmap.green_tools_flatten, "Whatsapp", "", FunType.WHATSAPP),
        )
    }

    fun getResultList(): List<HomeBean> {
        return listOf(
            HomeBean(R.mipmap.green_result_lonelys, "Battery Info", "", FunType.BATTERY),
            HomeBean(R.mipmap.green_result_hotel, "Large File", "", FunType.LARGE),
            HomeBean(R.mipmap.green_result_carrot, "App Process", "", FunType.PROCESS),

            HomeBean(R.mipmap.green_result_flatten, "Device Scan", "", FunType.DEVICE),
            HomeBean(R.mipmap.green_result_thirty, "Empty Files", "", FunType.EMPTY),

            HomeBean(R.mipmap.green_result_hospital, "Tiktok Clean", "", FunType.TIK),
            HomeBean(R.mipmap.green_result_careful, "Instagram Clean", "", FunType.INS),
            HomeBean(R.mipmap.green_result_lonely, "Telegram Clean", "", FunType.TEL),
            HomeBean(R.mipmap.green_result_flag, "Whatsapp", "", FunType.WHATSAPP),
        )
    }

    fun getTjList(funType: FunType?): HomeBean {
        val list = listOf(
            HomeBean(R.mipmap.green_tj_dirty, "Battery Info", "", FunType.BATTERY),
            HomeBean(R.mipmap.green_tj_thirty, "Large File", "", FunType.LARGE),
            HomeBean(R.mipmap.green_tj_flag, "App Process", "", FunType.PROCESS),

            HomeBean(R.mipmap.green_tj_flatten, "Device Scan", "", FunType.DEVICE),
            HomeBean(R.mipmap.green_tj_rain, "Empty Files", "", FunType.EMPTY),

            HomeBean(R.mipmap.green_tj_flatteny, "Tiktok Clean", "", FunType.TIK),
            HomeBean(R.mipmap.green_tj_loser, "Instagram Clean", "", FunType.INS),
            HomeBean(R.mipmap.green_tj_careful, "Telegram Clean", "", FunType.TEL),
            HomeBean(R.mipmap.green_tj_nut, "Whatsapp", "", FunType.WHATSAPP),
        )
        val result = ArrayList<HomeBean>()
        result.addAll(list.filter { it.funType != funType })
        result.shuffle()
        return result.take(1).first()
    }


    fun getMine(): List<MineBean> {
        return listOf(
            MineBean(R.mipmap.green_mine_ache, "About us", 0),
            MineBean(R.mipmap.green_mine_carrot, "Privacy Policy", 1),
        )
    }

    fun getDeviceList(): List<DeviceBean> {
        val number = MyDeviceUtils.getCpuCoresCount()
        return listOf(
            DeviceBean(
                "Mobile Phone", "${DeviceUtils.getManufacturer()}  ${DeviceUtils.getModel()}"
            ),
            DeviceBean("Cores Number", "$number"),
            DeviceBean("CPU Speed", "${MyDeviceUtils.getCpuSpeed()}"),
            DeviceBean("Percentage", "${MyDeviceUtils.getUsage(number)}"),
        )
    }

    fun getWifiList(context: Context): List<DeviceBean> {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        return listOf(
            DeviceBean("IP Address", "${NetworkUtils.getIPAddress(true)}"),
            DeviceBean("SSID", "${wifiInfo.ssid}"),
        )
    }

    fun getBatteryList(
        intent: Intent?, context: Context, powerCallBack: (power: String) -> Unit
    ): List<InfoBean> {
        val list = ArrayList<InfoBean>()
        intent?.let {
            val power = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 100)
            powerCallBack.invoke("$power")
            val health = when (intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0)) {
                BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE -> "UNSPECIFIED_FAILURE"
                BatteryManager.BATTERY_HEALTH_DEAD -> "DEAD"
                BatteryManager.BATTERY_HEALTH_OVERHEAT -> "OVERHEAT"
                BatteryManager.BATTERY_HEALTH_GOOD -> "GOOD"
                BatteryManager.BATTERY_HEALTH_COLD -> "COLD"
                BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE -> "OVER VOLTAGE"
                else -> "UNKNOWN"
            }
            val temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
            val voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)
            val totalCapacity: Int = MyDeviceUtils.getBatteryTotalPower(context)
            val currentCapacity = power * totalCapacity / 100

            list.add(InfoBean(R.mipmap.green_battery_flatten, "Battery Status", health))
            list.add(
                InfoBean(
                    R.mipmap.green_battery_hotel, "Temperature", "${temperature / 10.0}°C"
                )
            )
            list.add(
                InfoBean(
                    R.mipmap.green_battery_silk,
                    "Voltage",
                    "${(voltage / 1000.0).toString().substring(0, 3)}V"
                )
            )
            list.add(
                InfoBean(
                    R.mipmap.green_battery_simply, "Power", currentCapacity.toString() + "mAh"
                )
            )
            list.add(
                InfoBean(
                    R.mipmap.green_battery_though,
                    "Battery Type",
                    intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY) ?: ""
                )
            )
            list.add(
                InfoBean(
                    R.mipmap.green_battery_carrot, "Battery Capacity", "${totalCapacity}mAh"
                )
            )
        }
        return list
    }

    fun getProcessList(
        lifecycleScope: LifecycleCoroutineScope,
        context: Context,
        callBack: (list: ArrayList<AppInfo>) -> Unit
    ) {
        val dataList = arrayListOf<AppInfo>()
        lifecycleScope.launch(Dispatchers.IO) {
            context.packageManager.getInstalledPackages(0).forEach {
                if (((ApplicationInfo.FLAG_SYSTEM and it.applicationInfo.flags) == 0) && (ApplicationInfo.FLAG_UPDATED_SYSTEM_APP and it.applicationInfo.flags) == 0 && (ApplicationInfo.FLAG_STOPPED and it.applicationInfo.flags) == 0 && (context.packageName != it.packageName)) {
                    val icon = AppUtils.getAppIcon(it.packageName)
                    dataList.add(
                        AppInfo(
                            icon, AppUtils.getAppName(it.packageName), it.packageName
                        )
                    )
                }
            }
            withContext(Dispatchers.Main) {
                callBack.invoke(dataList)
            }
        }
    }

    fun getCleanScanList(): List<InfoBean> {
        return listOf(
            InfoBean(R.mipmap.green_scan_though, "Cache Garbage...", "0"),
            InfoBean(R.mipmap.green_scan_offer, "Uninstall Leftovers...", "0"),
            InfoBean(R.mipmap.green_scan_loser, "Temporary Files...", "0"),
            InfoBean(R.mipmap.green_scan_dirty, "Useless Package...", "0"),
        )
    }


    private var rootPath = Environment.getExternalStorageDirectory().absolutePath
    val telegramVideoPath = "$rootPath/Movies/Telegram"
    val telegramPicturePath = "$rootPath/Pictures/Telegram"
    val telegramCachePath = "$rootPath/Pictures/Telegram"
    val telegramDocumentPath = "$rootPath/Download/Telegram"
    val whatsappVideoPath = "$rootPath/WhatsApp/Media/WhatsApp Video"
    val whatsappPicturePath = "$rootPath/WhatsApp/Media/WhatsApp Images"
    val whatsappCachePath = "$rootPath/WhatsApp/Media/WhatsApp/Databases"
    val whatsappDocumentPath = "$rootPath/WhatsApp/Media/WhatsApp Documents"
    val tiktokVideoPath = "$rootPath/Android/data/com.zhiliaoapp.musically/cache/video"
    val tiktokPicturePath = "$rootPath/Android/data/com.zhiliaoapp.musically/cache/picture"
    val tiktokCachePath = "$rootPath/Android/data/com.zhiliaoapp.musically/files"
    val tiktokDocumentPath = "$rootPath/Android/data/com.ss.android.ugc.trill/files"
    val instagramVideoPath = "$rootPath/Android/data/com.instagram.android/cache/video"
    val instagramPicturePath = "$rootPath/Android/data/com.instagram.android/cache/picture"
    val instagramCachePath = "$rootPath/Android/data/com.instagram.android/files"
    val instagramDocumentPath = "$rootPath/Android/data/com.instagram.android/document"

    fun getTikList(funType: FunType?): List<TikBean> {

        var cachePath = ""
        var imagePath = ""
        var videoPath = ""
        var otherPath = ""

        when (funType) {
            FunType.TIK -> {
                cachePath = tiktokCachePath
                imagePath = tiktokPicturePath
                videoPath = tiktokVideoPath
                otherPath = tiktokDocumentPath
            }

            FunType.INS -> {
                cachePath = instagramCachePath
                imagePath = instagramPicturePath
                videoPath = instagramVideoPath
                otherPath = instagramDocumentPath
            }

            FunType.TEL -> {
                cachePath = telegramCachePath
                imagePath = telegramPicturePath
                videoPath = telegramVideoPath
                otherPath = telegramDocumentPath
            }

            FunType.WHATSAPP -> {
                cachePath = whatsappCachePath
                imagePath = whatsappPicturePath
                videoPath = whatsappVideoPath
                otherPath = whatsappDocumentPath
            }

            else -> {}
        }
        return listOf(
            TikBean(
                R.mipmap.green_tik_accidental, "Cache", cachePath, getDirSize(cachePath), false
            ),
            TikBean(R.mipmap.green_tik_simply, "Images", imagePath, getDirSize(imagePath), false),
            TikBean(R.mipmap.green_tik_accident, "Videos", videoPath, getDirSize(videoPath), false),
            TikBean(R.mipmap.green_tik_hotel, "Others", otherPath, getDirSize(otherPath), false),
        )
    }


    private fun getDirSize(path: String): Long {
        val file = File(path)
        if (FileUtils.isDir(file) && FileUtils.isFileExists(file)) {
            val dirSize = file.walkTopDown().map { it.length() }.sum()
            return dirSize
        }
        return 0L
    }
}